<?php

namespace App\Http\Controllers;

use App\Common\Curl;
use App\Models\WUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;

class IndexController extends Controller
{
    private $appID = 'wxdbb03f5a581f512c';
    private $appSecret = '7ab6df59ddccd3ab81629e84738dc8d7';

    public $event;

    public function __construct(EventController $event)
    {
        $this->event = $event;
    }

    public function test()
    {
        Cookie::queue(Cookie::forget('open_id'));
    }

    public function index(Request $request)
    {
        if(!Cookie::has('open_id')){
            $this->oauth($request);
        }
        View::addExtension('html','php');
        return \view()->file(public_path().'/index.html');
        // return $this->event->getEventData();
    }

    public function oauth($request)
    {
        $redirect_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $code = $request->code;
        $state = $request->state;

        if (!empty($code) && !empty($state)) {
            // 获取access_token 网页授权
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appID . "&secret=" . $this->appSecret . "&code={$code}&grant_type=authorization_code";

            $res = Curl::requestData($url, 'GET');
            $ret = json_decode($res, true);

            if (isset($ret['access_token']) && isset($ret['openid'])) {
                // 授权用户信息
//                $oauth_user_info = $this->getOauthUserInfo($ret['access_token'], $ret['openid']);
//                if (empty($oauth_user_info)) {
//                    die('授权失败,请检查昵称！');
//                }

                //设置cookie
                Cookie::queue('open_id',$ret['openid'],110);

                // 判断用户是否存在数据表中
                $userArr = WUser::where(['openid'=>$ret['openid']])->get();
                if($userArr->isEmpty()){
                    $dd = [
                        'openid' => $ret['openid'],
                        'nickname' => 1,
                        'sex' => 1,
                        'city' => 1,
                        'province' => 1,
                        'country' => 1,
                        'create_time' => date("Y-m-d H:i:s"),
                        'status' => 1,
                    ];
                    WUser::insert($dd);
                }
            }
        } else {
            //获取code
            $this->getCode($redirect_url);
        }

    }

    private function getCode($redirect_url)
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appID
            . '&redirect_uri=' . urlencode($redirect_url)
            . '&response_type=code&scope=snsapi_base&state=login#wechat_redirect';

        header("Location:" . $url);
        exit;
    }

    public function getOauthUserInfo($access_token, $open_id)
    {
        $oauth_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
        $res = Curl::requestData($oauth_url, 'GET');
        // $res = $this->_http->get($oauth_url);
        $oauth_user_info = json_decode($res, true);
        return $oauth_user_info;
    }

}
